package com.example.littleken.appmanager;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.littleken.appmanager.adapter.IUninstall;
import com.example.littleken.appmanager.adapter.MyAdapter;
import com.example.littleken.appmanager.entity.AppInfo;
import com.example.littleken.appmanager.util.Utils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,IUninstall, SearchView.OnQueryTextListener {

    ListView lv;
    List<AppInfo> list;
    MyAdapter adapter;

    public static final int SORT_NAME = 0;//定义排序方法
    public static final int SORT_DATE = 1;
    public static final int SORT_SIZE = 2;

    int currsort = SORT_NAME;//定义当前排序，默认按名字
    Comparator<AppInfo> currcomparator = null;//存储当前排序需要的比较器
    //定义三个比较器，用于应用排序
    //日期比较(倒序)
    Comparator<AppInfo> datecomparator = new Comparator<AppInfo>() {

        public int compare(AppInfo o1, AppInfo o2) {
            if(o1.insTime > o2.insTime){
                return -1;
            }else if(o1.insTime == o2.insTime){
                return 0;
            }else{
                return 1;
            }
        }
    };
    //大小比较(倒序)
    Comparator<AppInfo> sizecomparator = new Comparator<AppInfo>() {
        @Override
        public int compare(AppInfo o1, AppInfo o2) {
            if(o1.byteSize > o2.byteSize){
                return -1;
            }else if(o1.byteSize == o2.byteSize){
                return 0;
            }else{
                return 1;
            }
        }
    };

    //app名称比较(正序)
    Comparator<AppInfo> namecomparator = new Comparator<AppInfo>() {
        @Override
        public int compare(AppInfo o1, AppInfo o2) {
            return o1.appName.toLowerCase().compareTo(o2.appName.toLowerCase());
        }
    };

    TextView tv_msg_sort;
    TextView tv_msg_size;
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化视图控件
        lv = (ListView) findViewById(R.id.lv);
        tv_msg_size = (TextView) findViewById(R.id.tv_msg_size);
        tv_msg_sort = (TextView) findViewById(R.id.tv_msg_sort);
        //数据源准备
        //list = Utils.getAppList(this);
        //设置适配器
        adapter = new MyAdapter(this);
        //adapter.setList(list);

        lv.setAdapter(adapter);
        //Log.i("littleken","list="+list.toString());
        lv.setOnItemClickListener(this);//设置点击事件
        adapter.setUninstall(this);

        updateData();
    }

    //存放排序名称
    public static final String[] arr_sort={"按名称排序","按安装时间排序","按软件大小排序"};
        private void update_top_msg(){//更新表头数据
            tv_msg_size.setText("app数量:"+list.size());
            tv_msg_sort.setText("排序方式:"+arr_sort[currsort]);
/*       String sort = "";
        if(currsort==SORT_NAME){
            sort = "按名称排序";
        }else if(currsort==SORT_DATE){
            sort = "按安装时间排序";
        }else {
            sort = "按软件大小排序";
        }*/
        //tv_msg_sort.setText("排序方式:"+sort);
    }

    SearchView sv;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //反射获得菜单xml布局
        getMenuInflater().inflate(R.menu.menu_main,menu);
        MenuItem search = menu.findItem(R.id.search);
       // sv = (SearchView) MenuItemCompat.getActionView(search);
//     通过这种方法得到的SearchView无法展开，只能使用下面new的方法
        sv = new SearchView(this);
        search.setActionView(sv);
        //设置searchview关闭事件
        //用MenuItemCompat来添加
        MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {//展开
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {//折叠
                updateData();
                return true;
            }
        });
/*         if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){//判断版本
             MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() {
                @Override
                public boolean onMenuItemActionExpand(MenuItem item) {//展开
                    return true;
                }

                @Override
                public boolean onMenuItemActionCollapse(MenuItem item) {//折叠
                    updateData();
                    return true;
                }
            });
        }else{
            sv.setOnCloseListener(new SearchView.OnCloseListener() {
                @Override
                public boolean onClose() {
                    updateData();
                    return true;
                }
            });
        }*/
        sv.setSubmitButtonEnabled(true);//设置可提交，提交内容为文本
        sv.setQueryHint("查找应用");//设置提示内容
        sv.setOnQueryTextListener(this);//设置文本提交监听器,让MainActivity实现接口并重新抽象方法


        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //设置菜单点击监听
        //int id = item.getItemId();
        switch (item.getItemId()){
            case R.id.sort_name:
                Toast.makeText(MainActivity.this,"按名字排序",Toast.LENGTH_SHORT).show();
                //Collections.sort(list,namecomparator);//通过Collections.sort将list进行排序，排序规则传入对应比较器
                currsort = SORT_NAME;//通过改变变量的形式改变排序形式
                break;
            case R.id.sort_date:
                Toast.makeText(MainActivity.this,"按安装时间排序",Toast.LENGTH_SHORT).show();
                //Collections.sort(list,datecomparator);
                currsort = SORT_DATE;
                break;
            case R.id.sort_size:
                Toast.makeText(MainActivity.this,"按大小排序",Toast.LENGTH_SHORT).show();
                //Collections.sort(list,sizecomparator);
                currsort = SORT_SIZE;
                break;
            case R.id.refresh:
                updateData();//重新加载数据
                break;
        }
        updatedate_sort(currsort);//刷新列表
        return true;
    }

    private void updatedate_sort(int sort){//用于排序之后的刷新
        if(sort == SORT_NAME){
            currcomparator = namecomparator;
        }else if(sort == SORT_DATE){
            currcomparator = datecomparator;
        }else{
            currcomparator = sizecomparator;
        }
        Collections.sort(list,currcomparator);//排序
        adapter.setList(list);//重新传入排好序的list
        adapter.notifyDataSetChanged();//原地刷新
        update_top_msg();//刷新表头
    }

    ProgressDialog pd;
    public void showProgressDialog(){
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setTitle("刷新列表");
        pd.setMessage("请耐心等待");
        pd.show();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            /*adapter.setList(list);
            adapter.notifyDataSetChanged();//原地刷新*/
             updatedate_sort(currsort);
            //Log.i("littleken","list="+list.toString());
            pd.dismiss();
        }
    };

    //通过新建线程，让ui与耗时操作同步进行，让ui不阻塞
    private void updateData(){
        //两个操作同步进行
        new Thread(){//耗时操作
            @Override
            public void run() {
                list = Utils.getAppList(MainActivity.this);//最耗时操作，读取所有app信息
                KEYWORD = null;//清空搜索关键字
                handler.sendEmptyMessage(1);//通知主线程，子线程以完成操作
            }
        }.start();
        showProgressDialog();//ui显示
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//实现接口，实现item短点击监听
        AppInfo app = (AppInfo) parent.getItemAtPosition(position);//反向获取到本item信息
        if(!Utils.openPackage(this,app.packageName)){
            Toast.makeText(MainActivity.this,"软件打开错误",Toast.LENGTH_SHORT).show();
        }
    }

    public  static final int CODE_UNINSTALL = 0;
    public void btnOnClick(int pos, String packageName) {
        Utils.uninstallApp(this,packageName,CODE_UNINSTALL);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {//实现接口，完成删除后，接收回传参数，然后刷新
        if(requestCode==CODE_UNINSTALL){
            //刷新
            updateData();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static String KEYWORD = null;//搜索关键字
    @Override
    public boolean onQueryTextSubmit(String query) {//实现接口，监听SearchView文本提交
        //实现搜索
        //Toast.makeText(MainActivity.this,query,Toast.LENGTH_SHORT).show();
        KEYWORD = query;
        list = Utils.getSearchResult(list,query);//实现不断缩小范围的查询
        updatedate_sort(currsort);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {//实现接口，监听searchView的动作
        return true;
    }
}
